import requests
import json
from config import Config

class EnglishAITutor:
    def __init__(self):
        self.api_key = Config.MAAS_API_KEY
        self.base_url = Config.BASE_URL.rstrip('/')  # 移除末尾的斜杠
        self.model = Config.MODEL
        print(f"✅ 初始化AI导师，Base URL: {self.base_url}")
        print(f"✅ 模型: {self.model}")
        print(f"✅ API Key: {self.api_key[:10]}...")  # 只显示前10位
    
    def _make_request(self, data):
        """统一的请求方法，优化超时设置"""
        try:
            # 确保 base_url 格式正确
            endpoint = f"{self.base_url}/chat/completions"
            print(f"📤 发送请求到: {endpoint}")
            
            # 手动处理 JSON 编码，确保使用 UTF-8
            json_data = json.dumps(data, ensure_ascii=False, separators=(',', ':'))
            json_bytes = json_data.encode('utf-8')
            
            headers = {
                "Content-Type": "application/json; charset=utf-8",
                "Authorization": f"Bearer {self.api_key}",
                "Accept": "application/json"
            }
            
            print(f"📝 请求数据长度: {len(json_bytes)} bytes")
            
            # 使用更长的超时时间
            response = requests.post(
                endpoint,
                headers=headers,
                data=json_bytes,
                timeout=60.0,  # 增加到60秒超时
                verify=True  # 确保SSL验证
            )
            
            print(f"📥 响应状态码: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                print("✅ 请求成功")
                return result
            elif response.status_code == 401:
                print("❌ 认证失败：API密钥无效")
                return None
            elif response.status_code == 404:
                print("❌ 端点不存在：请检查Base URL")
                return None
            elif response.status_code == 429:
                print("❌ 请求频率限制：请稍后重试")
                return None
            elif response.status_code >= 500:
                print("❌ 服务器错误：API服务暂时不可用")
                return None
            else:
                print(f"❌ API 响应错误: {response.status_code}")
                print(f"响应内容: {response.text[:500]}")  # 只显示前500字符
                return None
                
        except requests.exceptions.Timeout:
            print("❌ 请求超时（60秒），API响应过慢")
            return None
        except requests.exceptions.ConnectionError as e:
            print(f"❌ 连接错误: {e}")
            return None
        except requests.exceptions.SSLError as e:
            print(f"❌ SSL错误: {e}")
            return None
        except Exception as e:
            print(f"❌ 请求异常: {str(e)}")
            return None
    
    def chat(self, messages, temperature=0.7, max_tokens=1000):
        """基础聊天功能"""
        # 确保所有消息内容都是字符串
        safe_messages = []
        for msg in messages:
            safe_msg = {
                "role": str(msg["role"]),
                "content": str(msg["content"])
            }
            safe_messages.append(safe_msg)
        
        data = {
            "model": self.model,
            "messages": safe_messages,
            "temperature": temperature,
            "max_tokens": max_tokens
        }
        
        print("💬 发送聊天消息...")
        result = self._make_request(data)
        
        if result and "choices" in result and len(result["choices"]) > 0:
            content = result["choices"][0]["message"]["content"]
            print(f"✅ 收到AI回复: {content[:100]}...")  # 只显示前100字符
            return content
        else:
            error_msg = "抱歉，AI服务暂时不可用。可能是网络连接问题或API服务繁忙，请稍后重试。"
            print(f"❌ {error_msg}")
            return error_msg
    
    def correct_grammar(self, text):
        """语法纠错"""
        prompt = f"Correct this English sentence and explain: {text}"
        
        return self.chat([
            {"role": "system", "content": "You are an English grammar teacher. Correct errors and explain briefly."},
            {"role": "user", "content": prompt}
        ], max_tokens=500)
    
    def explain_vocabulary(self, word):
        """词汇解释"""
        prompt = f"Explain this word: {word}"
        
        return self.chat([
            {"role": "system", "content": "You are an English teacher. Explain words clearly and concisely."},
            {"role": "user", "content": prompt}
        ], max_tokens=500)
    
    def practice_conversation(self, scenario="restaurant"):
        """情景对话练习"""
        prompt = f"Start a short conversation in a {scenario}"
        
        return self.chat([
            {"role": "system", "content": f"You are in a {scenario}. Keep responses short and natural."},
            {"role": "user", "content": prompt}
        ], temperature=0.9, max_tokens=300)
    
    def test_connection(self):
        """测试连接"""
        print("🧪 测试AI连接...")
        test_response = self.chat([
            {"role": "user", "content": "Say 'Hello'"}
        ], max_tokens=50)
        return test_response